//
//  TIMCustomMenu.m
//  Demo_sdk
//
//  Created by Deli Xia on 2018/7/12.
//  Copyright © 2018年 Deli Xia. All rights reserved.
//

#import "TIMCustomMenu.h"
#import "TIMDemoMacro.h"
#import "TIMCustomMenuItem.h"
#import "NSDate+Extensions.h"

@implementation TIMCustomMenu

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        [self init_TPSCustomMenu];
    }
    return self;
}

- (void)init_TPSCustomMenu {
    
    self.titles = [NSMutableArray new];
    
    [self addSubview:self.backgroundImageView];
    [self addSubview:self.arrowImageView];
    
    UICollectionViewFlowLayout *layout = [UICollectionViewFlowLayout new];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor clearColor];
    self.collectionView.showsVerticalScrollIndicator = FALSE;
    self.collectionView.showsHorizontalScrollIndicator = FALSE;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    [self.collectionView registerClass:[TIMCustomMenuItem class] forCellWithReuseIdentifier:[TIMCustomMenuItem description]];
    [self addSubview:self.collectionView];
    
}

#pragma mark - UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.titles.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    TIMCustomMenuItem *item = [collectionView dequeueReusableCellWithReuseIdentifier:[TIMCustomMenuItem description] forIndexPath:indexPath];
    item.titleLabel.text = self.titles[indexPath.row];
    return item;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    [collectionView deselectItemAtIndexPath:indexPath animated:YES];
    NSString *title = self.titles[indexPath.row];
    if ([title isEqualToString:@"复制"]) {
        [self p_clickedMenuItemType:TPSChatMenuItemTypeCopy];
    } else if ([title isEqualToString:@"转发"]) {
        [self p_clickedMenuItemType:TPSChatMenuItemTypeRelay];
    } else if ([title isEqualToString:@"删除"]) {
        [self p_clickedMenuItemType:TPSChatMenuItemTypeDelete];
    } else if ([title isEqualToString:@"撤回"]) {
        [self p_clickedMenuItemType:TPSChatMenuItemTypeRevoke];
    }
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake(55, 35);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    return 0;
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsZero;
}

#pragma mark -
- (void)showInView:(UIView *)view withMessage:(TIMMessage *)message rect:(CGRect)rect actionBlock:(void (^)(TPSChatMenuItemType))actionBlock {
    [view addSubview:self.menuBackView];
    [view addSubview:self];
    self.menuBackView.frame = view.bounds;
    
    _isShow = YES;
    [self setActionBlcok:actionBlock];
    [self setMessage:message];
    
    CGFloat screenW = [UIScreen mainScreen].bounds.size.width;
    CGFloat screenH = [UIScreen mainScreen].bounds.size.height;
    CGFloat itemW = AUTO_WIDTH(55);
    // 保证箭头在rect中心
    CGFloat targetCenterX = rect.origin.x + rect.size.width/2;
    CGFloat menuW = self.titles.count * itemW;
    CGFloat menuH =  35;
    CGFloat menuX = targetCenterX - menuW/2 > 8 ? targetCenterX - menuW/2 : 8;
    
    menuX = menuX + menuW > screenW ? screenW - menuW - 8 : menuX;
    CGFloat menuY = rect.origin.y - menuH;
    // 避免 MenuController 过于靠上
    menuY = menuY < 20 ? rect.origin.y + rect.size.height : menuY;
    // 适配特别长的文本，直接显示在屏幕中间
    menuY = menuY > screenH-menuH-30 ? screenH / 2 : menuY;
    
    CGRect frame = CGRectMake(menuX, menuY, menuW, menuH);
    
    [self setFrame:frame];
    CGFloat arrowH = 8;
    CGFloat arrowW = 12;
    CGFloat arrowX = rect.origin.x-frame.origin.x+0.5*rect.size.width-arrowW/2;
    
    if (frame.origin.y > rect.origin.y) {
        // 箭头向上
        self.backgroundImageView.frame = CGRectMake(0, arrowH, menuW, menuH-arrowH);
        self.arrowImageView.image = [UIImage imageNamed:@"longpress_up_arrow"];
        self.arrowImageView.frame = CGRectMake(arrowX, 0, arrowW, arrowH);
    } else {
        // 箭头向下
        self.backgroundImageView.frame = CGRectMake(0, 0, menuW, menuH-arrowH);
        self.arrowImageView.image = [UIImage imageNamed:@"longpress_down_arrow"];
        self.arrowImageView.frame = CGRectMake(arrowX, menuH-arrowH, arrowW, arrowH);
    }
    self.collectionView.frame = self.backgroundImageView.frame;
    
//    if (message.messageType == TPSMessageTypeVoice || message.messageType == TPSMessageTypeSnapshotVoice) {
//        if ([(TPSVoiceMessage *)message msgStatus] != TPSVoiceMessageStatusNormal) {
//            [[TPSAudioPlayer sharedAudioPlayer] stopPlayingAudio];   // 停止播放语音消息
//        }
//    }
    [self.collectionView reloadData];
}


- (void)setMessage:(TIMMessage *)message {
    NSString *copy = @"复制";
    NSString *transmit = @"转发";
    NSString *del = @"删除";
    NSString *revoke = @"撤回";
    
    NSArray *menuItems;
//    double time = [NSDate DvalueTimeInfoWithDate:message.date];
    
    if (message.ownerTyper == TIMMessageOwnerTypeSelf) {
        
//        if (time > 120) {
//            revoke = del;
//        }
        switch (message.messageType) {
            case TIMMessageTypeText:
                menuItems = @[del, transmit, revoke];
                break;
//            case TPSMessageTypeImage:
//                menuItems = @[transmit, revoke];
//                break;
//            case TPSMessageTypeExpression:
//                menuItems = @[transmit, revoke];
//                break;
//            case TPSMessageTypeVoice:
//                menuItems = @[revoke] ;
//                break;
//            case TPSMessageTypeSnapshotText:
//                menuItems = @[copy, transmit, revoke];
//                break;
//            case TPSMessageTypeSnapshotPhoto:
//                menuItems = @[transmit, revoke];
//                break;
//            case TPSMessageTypeSnapshotExpression:
//                menuItems = @[transmit, revoke];
//                break;
//            case TPSMessageTypeSnapshotVoice:
//                menuItems = @[revoke] ;
//                break;
            default:
                menuItems = @[revoke];
                break;
        }
        
    } else if (message.ownerTyper == TIMMessageOwnerTypeFriend) {
        
        switch (message.messageType) {
            case TIMMessageTypeText:
                menuItems = @[del, transmit, revoke];
                break;
//            case TPSMessageTypeImage:
//                menuItems =  @[transmit, del];
//                break;
//            case TPSMessageTypeExpression:
//                menuItems = @[transmit, del];
//                break;
//            case TPSMessageTypeVoice:
//                menuItems = @[del] ;
//                break;
//            case TPSMessageTypeSnapshotText:
//                menuItems = @[del];
//                break;
//            case TPSMessageTypeSnapshotPhoto:
//                menuItems =  @[del];
//                break;
//            case TPSMessageTypeSnapshotExpression:
//                menuItems = @[del];
//                break;
//            case TPSMessageTypeSnapshotVoice:
//                menuItems = @[del] ;
//                break;
            default:
                menuItems = @[del];
                break;
        }
    }
    [self.titles removeAllObjects];
    [self.titles addObjectsFromArray:menuItems];
}

- (void)touchOutSide
{
    if (self) {
        [self dismiss];
    }
}
- (void)dismiss {
    _isShow = NO;
    if (self.actionBlcok) {
        self.actionBlcok(TPSChatMenuItemTypeCancel);
    }
    [self removeFromSuperview];
    [_menuBackView removeFromSuperview];
}

- (void)p_clickedMenuItemType:(TPSChatMenuItemType)type {
    _isShow = NO;
    [self removeFromSuperview];
    [_menuBackView removeFromSuperview];
    if (self.actionBlcok) {
        self.actionBlcok(type);
    }
}
- (UIImageView *)backgroundImageView {
    if (!_backgroundImageView) {
        _backgroundImageView = [[UIImageView alloc] init];
        UIImage *bgImage = [UIImage imageNamed:@"longpress_bg"];
        _backgroundImageView.image = bgImage;
        _backgroundImageView.userInteractionEnabled = YES;
    }
    return _backgroundImageView;
}

- (UIImageView *)arrowImageView {
    if (!_arrowImageView) {
        _arrowImageView = [[UIImageView alloc] init];
    }
    return _arrowImageView;
}
- (UIView *)menuBackView {
    if (_menuBackView == nil) {
        _menuBackView = [[UIView alloc] init];
        _menuBackView.backgroundColor = [UIColor clearColor];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget: self action: @selector(touchOutSide)];
        [_menuBackView addGestureRecognizer: tap];
    }
    return _menuBackView;
}

@end
